package com.smartcruise.start.flashActivity;

import android.os.Handler;
import android.text.TextUtils;

import com.smartcruise.data.UserInfo;
import com.smartcruise.util.Key;
import com.smartcruise.util.SPUtils;

/**
 * Created by FengChaoQun
 * on 2018/1/18 0018
 */

public class FlashPresenterImp implements FlashContract.Presenter {

    private final long delayTime = 1500;  //闪屏页面显示时间
    private FlashContract.View view;
    private Handler handler;
    private Runnable runnable;

    public FlashPresenterImp(FlashContract.View view) {
        this.view = view;
        handler = new Handler(view.getActivity().getMainLooper());
    }

    @Override
    public void start() {
        runnable = new Runnable() {
            @Override
            public void run() {
                if (isNeedLogin()) {
                    view.gotoLoginActivity();
                } else {
                    view.gotoMainActivity();
                }
            }
        };
        handler.postDelayed(runnable, delayTime);
    }

    /**
     * description:判断是否需要登录
     * 1.本地没有存储用户账号的时候需要登录
     * 2.用户退出登录后需要重新登录
     * 3.本地没有用户信息时需要重新登录
     */

    private boolean isNeedLogin() {
        if (TextUtils.isEmpty(SPUtils.getLastAccount())) {
            return true;
        }
        if (SPUtils.isQuit()) {
            return true;
        }

        UserInfo userInfo = view.getRealm().where(UserInfo.class).equalTo(Key.id, SPUtils.getLastAccount()).findFirst();
        return userInfo == null;

    }

    /**
     * description:页面销毁的时候将延时任务取消
     */

    @Override
    public void destroy() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }
}
